package com.timmy.bluetooth.connect;

import android.content.Context;
import android.os.Handler;
import android.util.Log;

import com.timmy.bluetooth.thread.ThreadPoolController;
import com.timmy.bluetooth.utils.DebugLog;
import com.timmy.bluetooth.utils.Hex;


/**
 * Created by sandy on 16/4/13.
 */
public class BluetoothConnectClientManager implements Runnable {
    public static BluetoothConnectClientManager instance = null;

    /**
     * 数据默认发送频率
     */
    public static final int DEFALUT_PERIOD_NON_SHOCK_1S = 500;
    public static final int DEFALUT_PERIOD_SHOCK_100MS = 100;

    public enum ConnectStatus {
        STATUS_OK,
        STATUS_FAIL
    }

    /**
     * 蓝牙管理引用
     */
    public  IBluetoothManager iBluetoothManager;

    /**
     * 设备地址
     */
    private String deviceAddress;

    /**
     * 蓝牙连接监听引用
     */
     IBluetoothConnectListener listener;
    /**
     * handler 推送到ui线程中
     */
    Handler handler = new Handler();

    /**
     * 命令数据类引用
     */
     ICommand command;

    /**
     * 数据传送周期
     */
    int period = DEFALUT_PERIOD_NON_SHOCK_1S;

    /**
     * 是否使能数据传输
     */
    private boolean isSendingData = false;

    /**
     * 上下文
     */
    private Context context;

    /**
     * 是否连接
     */
    private boolean isConnected = false;


    private boolean isReconnect = false;

    /**
     * 蓝牙数据接受监听器
     */
     IBluetoothReceiveDataListener dataListener;

    /**
     * 按摩时间监听器
     */
     OnShockUseTimeListener onShockUseTimeListener;

    /**
     * 是否接受到数据
     */
    private boolean isReceiveData = true;

    /**
     * 定时器引用
     */
    private  LoopTimer loopTimer;

    private BluetoothConnectClientManager() {
    }

    public void setBluetoothReceiveDataListener( IBluetoothReceiveDataListener dataListener) {
        this.dataListener = dataListener;
    }

    public void setOnBluetoothConnectListener( IBluetoothConnectListener listener) {
        this.listener = listener;
    }

    public void setOnShockUseTimeListener( OnShockUseTimeListener onShockUseTimeListener) {
        this.onShockUseTimeListener = onShockUseTimeListener;
    }

    public static synchronized BluetoothConnectClientManager getInstance() {
        if (instance == null) {
            instance = new BluetoothConnectClientManager();
        }
        return instance;
    }

    /**
     * 数据命令
     */
    public void setCommand( Command command) {
        this.command = command;
    }

    /**
     * 开启蓝牙连接， 会自建线程处理， 耗时操作。
     *
     * @param 上下文
     * @return 蓝牙设备地址
     */
    public void BleInited(Context context, String deviceAddress) {

        Log.i("连接", "BleInited: 开始连接设备");

        this.context = context;

        this.deviceAddress = deviceAddress;

        //初始化计数器
        loopTimer = new  LoopTimer(loopTimerListener, 1000);

        //获取蓝牙管理服务
        iBluetoothManager = new  BluetoothServer();

        //开始连接设备
        new Thread(conRunable).start();
    }

    public void BleDeinited() {

         DebugLog.d("finsih...");

        closeReceiveChannel();

        isConnected = false;

        if (iBluetoothManager != null) {
            //断开连接
            iBluetoothManager.disconnect();
            iBluetoothManager.close();

//            iBluetoothManager = null;
        }

        if (loopTimer != null) {
            if (loopTimer.isTimering()) {
                loopTimer.stopTimer();
            }

        }

        closeDetect();
    }

    /**
     * 获取版本号
     *
     * @return 是否成功
     */
    public boolean getVersionInfo() {

        if (iBluetoothManager != null)
            return iBluetoothManager.getVersion();

        return false;
    }

    public boolean isConnected() {
        return isConnected;
    }

    public void stopBleConnect() {

        //    if(isConnected)
        if (iBluetoothManager != null) {
            iBluetoothManager.disconnect();
            iBluetoothManager.close();
        }

        isReconnect = false;

        if (loopTimer != null)
            loopTimer.stopTimer();
    }

    Runnable conRunable = new Runnable() {
        @Override
        public void run() {
            if (!iBluetoothManager.initialize(context)) {
                return;
            }
            // Automatically connects to the device upon successful start-up
            // initialization.
            iBluetoothManager.addClientCallback(mCallback);
            iBluetoothManager.connect(context, deviceAddress);
            //start timing.
            loopTimer.startTimer();
        }
    };

    public void reConnect(Context context) {
        if (!iBluetoothManager.getConnectStatus()) {
            isReconnect = true;
            iBluetoothManager.connect(context, deviceAddress);

            if (!loopTimer.isTimering()) {
                loopTimer.startTimer();
            }
             DebugLog.i("reconnecting.....");
        }

    }


     BluetoothServiceCallback mCallback = new  BluetoothServiceCallback() {
        @Override
        public void onConnectStatus(final ConnectStatus status) {
            if (status == ConnectStatus.STATUS_OK) {
                //成功连接上设备
                isConnected = true;
                isReconnect = false;

                loopTimer.stopTimer();

                //open the receive channel.
                openReceiveChannel();

                //openSendChannel();

                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (listener != null) {
                            listener.onConnect(status);
                        }
                    }
                });

            } else {

                if (listener != null && !isConnected && !isReconnect) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            listener.onConnect(status);
                        }
                    });
                }

                //失败连接或断开连接
                isConnected = false;
            }

        }

        @Override
        public void onReceive(byte[] data) {
            Log.i("解析数据", "onReceive: " +  Hex.bytesToHexString(data));
            isReceiveData = true;
            if (dataListener != null)
                dataListener.onBLEReceiveData(data);
        }

        @Override
        public void onVersion(byte[] msg) {

            Log.i("解析数据", "onVersion: " +  Hex.bytesToHexString(msg));
            if (dataListener != null)
                dataListener.onVersion(msg);
        }
    };

    public void openDetectRemoteDeviceIsDisconnect() {
        isReceiveData = true;
        detectIsDisconnect();
    }

    public void closeDetectRemoteDeviceIsDisconnect() {
        closeDetect();
    }

    private void closeDetect() {
        handler.removeCallbacks(detectRun);
    }

    private void detectIsDisconnect() {
        handler.postDelayed(detectRun, 4000);
    }

    public void openReceiveChannel() {
        if (iBluetoothManager != null) {
             DebugLog.e("enable receive data....");
            iBluetoothManager
                    .setCharacteristicNotification(true);
        }
    }

    private void closeReceiveChannel() {
        if (iBluetoothManager != null) {
             DebugLog.e("disable receive data....");
            iBluetoothManager
                    .setCharacteristicNotification(false);
        }
    }

    Runnable detectRun = new Runnable() {
        @Override
        public void run() {
            if (isReceiveData && isConnected) {
                isReceiveData = false;
                handler.postDelayed(this, 4000);
            } else if (listener != null) {
                isReceiveData = true;
                isConnected = false;
                stopBleConnect();
                 DebugLog.e("没有数据断开了。。。。");
                listener.onConnect(ConnectStatus.STATUS_FAIL);
            }
        }
    };

    public void openSendChannel() {

        //delivery thread to send control data.     //线程池
         ThreadPoolController.execute(this);
    }

    public void setSendPeriod(int ms) {
        period = ms;
    }

     ILoopTimerListener loopTimerListener = new  ILoopTimerListener() {
        @Override
        public void onLoopTimer() {

            handler.post(new Runnable() {
                @Override
                public void run() {
                    //蓝牙连接时间
                    if (listener != null)
                        listener.onTimer1s();
                }
            });

        }
    };


    @Override
    public void run() {
        Thread thread = Thread.currentThread();

        while (isConnected) {

            byte data[] = command.getData();

            //bluetooth send data.
            iBluetoothManager.WriteData(data);

            try {
                Thread.sleep(period);
            } catch (InterruptedException e) {
                 DebugLog.e(e.getMessage());
                thread.interrupt();
            }
        }

        //get current thread and interrupt it.
        thread.interrupt();
    }
}
